import 'package:flutter/material.dart';
import 'loading_widget.dart';

class LoadingTip {
  static OverlayEntry? _holder;

  static late BuildContext _context;

  static bool _isMask = false;

  static bool _loading = false;

  static bool get loading => _loading;

  static void show({
    required BuildContext context,
    String title = '加载中...',
    bool isMask = false,
    Color barrierColor = const Color(2147483648),
    bool ableBack = false,
  }) {
    _context = context;
    _isMask = isMask;
    if (_isMask) {
      _showWithMask(
        context: context,
        title: title,
        barrierColor: barrierColor,
        ableBack: ableBack,
      );
    } else {
      _showWithoutMask(
        context: context,
        title: title,
      );
    }
  }

  // 需要遮罩层
  static void _showWithMask({
    required BuildContext context,
    required String title,
    required Color barrierColor,
    required bool ableBack,
  }) {
    showGeneralDialog(
      context: context,
      barrierDismissible: false,
      barrierColor: barrierColor,
      transitionDuration: Duration(milliseconds: 0),
      pageBuilder: (BuildContext context, _, __) {
        _loading = true;
        return WillPopScope(
          child: Center(
            child: LoadingWidget(
              title: title,
            ),
          ),
          onWillPop: () async {
            _loading = false;
            return Future.value(ableBack);
          },
        );
      },
    );
  }

  // 不需要遮罩层
  static void _showWithoutMask({
    required BuildContext context,
    required String title,
  }) {
    remove();
    OverlayEntry overlayEntry = OverlayEntry(
      builder: (context) {
        return LoadingWidget(
          title: title,
        );
      },
    );

    Overlay.of(context)!.insert(overlayEntry);

    _holder = overlayEntry;

    _loading = true;
  }

  static void remove() {
    if (!_loading) return;

    if (_isMask) {
      Navigator.pop(_context);
    } else {
      if (_holder != null) {
        _holder?.remove();
        _holder = null;
      }
    }

    _loading = false;
  }
}
